<template>
  <!-- destroyOnClose仅仅是清除了模态框里的dom，但是pagemodal这个组件里的数值没有清楚，导致初始化异常 -->
  <a-modal
    class="choose_url"
    width="1500px"
    :title="pagetitle"
    :visible="pageVisible"
    :destroyOnClose="true"
    :maskClosable="false"
    :keyboard="false"
    @cancel="closeModal"
    :confirmLoading="confirmLoading"
  >
    <template slot="footer">
      <a-button key="back" @click="closeModal"> 取消 </a-button>
      <a-button key="submit" type="primary" @click="handleSubmit">
        确定
      </a-button>
    </template>
    <div class="searchBox">
      <a-input-search
        placeholder="请输入优惠券名称"
        style="width: 200px"
        v-model="searchParams.couponName"
        @search="onSearch"
      />
      <a-button
        type="primary"
        style="margin-left: 10px"
        @click="onSearch"
        :loading="tableLoading"
      >
        搜索
      </a-button>
      <a-button
        style="margin-left: 10px"
        @click="resetSearch"
        :loading="tableLoading"
        >重置</a-button
      >
    </div>
    <a-table
      rowKey="id"
      :row-selection="rowSelection"
      :columns="columns"
      :data-source="pageList"
      :pagination="pagination"
      @change="tableChange"
      :loading="tableLoading"
    ></a-table>
  </a-modal>
</template>

<script>
import { findDictNameByValue } from "@/utils/dict";
export default {
  name: "giftChoose",
  props: {
    pageVisible: {
      type: Boolean,
      default: false,
    },
    pageModelId: {
      type: String,
      default: "",
    },
    pagetitle: {
      type: String,
      default: "选择优惠券",
    },
    goodsInfo: {
      type: Object,
      default: {},
    },
    tableData: {
      type: Array,
      default: [],
    },
  },
  created() {},
  data() {
    return {
      selectedRowsInfo: {}, // 选中的页面信息
      loading: false,
      confirmLoading: false,
      tableLoading: false,
      pageList: [],
      selectedRowKeys: [],
      pagination: {
        showQuickJumper: true,
        total: 0,
        current: 1,
        pageSize: 10,
        showTotal: (total) => `共${total}条`,
        showSizeChanger: true,
        pageSizeOptions: ["10", "20", "50", "100", "200"],
      },
      columns: [
        {
          title: "优惠券名称",
          dataIndex: "couponName",
          key: "couponName",
          width: 200,
        },
        {
          title: "优惠券类型",
          dataIndex: "couponType",
          key: "couponType",
          width: 120,
          // customRender: (text) => {
          //   if (text == 0) {
          //     return "减满劵";
          //   } else if (text == 1) {
          //     return "礼品劵";
          //   } else if (text == 2) {
          //     return "折扣劵";
          //   }
          //   return "";
          // },
          customRender: (text, record) =>
            findDictNameByValue("COUPON_TYPE", text),
        },
        {
          title: "优惠内容",
          dataIndex: "couponAmount",
          key: "couponAmount",
          width: 150,
          customRender: (value, row) => {
            if (row.couponType == 0 || row.couponType == 1) {
              return "优惠金额" + value + "元";
            } else if (row.couponType == 2) {
              return "打" + row.discountRatio + "折";
            }
            return value;
          },
        },
        {
          title: "使用条件",
          dataIndex: "couponFullMoney",
          key: "couponFullMoney",
          width: 200,
          customRender: (text, row) => {
            // 1、订单满xx元可用，最多优惠xx钱（使用门槛和最多优惠都不为-1）
            // 2、无门槛，最多优惠xx钱（使用门槛为-1，最多优惠不为-1）
            // 3、订单满xx元可用（最多优惠为-1，使用门槛不为-1）
            // 4、无门槛（使用门槛为-1，最多优惠也为-1）
            if (row.couponFullMoney != -1 && row.mostDiscount != -1) {
              return `订单满${row.couponFullMoney}元可用，最多优惠${row.mostDiscount}元`;
            } else if (row.couponFullMoney == -1 && row.mostDiscount != -1) {
              return `无门槛，最多优惠${row.mostDiscount}元`;
            } else if (row.couponFullMoney != -1 && row.mostDiscount == -1) {
              return `订单满${row.couponFullMoney}元可用`;
            } else if (row.couponFullMoney == -1 && row.mostDiscount == -1) {
              return "无门槛";
            }
            return "";
          },
        },
        {
          title: "状态",
          dataIndex: "couponStatus",
          key: "couponStatus",
          width: 100,
          customRender: (text, row) => {
            if (row.couponStatus == 0) {
              return row.couponIngStatus;
              // let currentTime = new Date().getTime();
              // if (
              //   currentTime > this.getTimestamp(row.getStartTime) &&
              //   currentTime < this.getTimestamp(row.useEndTime)
              // ) {
              //   return "进行中";
              // } else if (currentTime > this.getTimestamp(row.useEndTime)) {
              //   return "已结束";
              // } else if (currentTime < this.getTimestamp(row.getStartTime)) {
              //   return "未开始";
              // }
            } else {
              return "已结束";
            }
          },
        },
        {
          title: "领取人次",
          dataIndex: "couponIssueNum",
          key: "couponIssueNum",
          width: 100,
        },
        {
          title: "库存",
          dataIndex: "couponStocks",
          key: "couponStocks",
          width: 100,
          customRender: (text, row) => {
            if (text == -1) {
              return "不限量";
            } else if (text == 0) {
              return "库存不足";
            }
            return text;
          },
        },
        {
          title: "创建时间",
          dataIndex: "createDate",
          key: "createDate",
        },
        {
          title: "失效时间",
          dataIndex: "useTimeType",
          key: "useTimeType",
          width: 160,
          customRender: (text, row) => {
            let res = "";
            if (text == 3) {
              res = "永久有效";
            } else if (text == 2) {
              res = "领券当日起" + row.receiveDaysAble + "内有效";
            } else {
              if (row.useEndTime) {
                res = row.useEndTime;
              } else {
                res = "";
              }
            }
            return res;
          },
        },
      ],
      disableId: [],
      searchParams: {
        couponName: "",
      },
    };
  },

  computed: {
    rowSelection() {
      return {
        selectedRowKeys: this.selectedRowKeys,
        type: "radio",
        onChange: this.onSelectChange,
        // getCheckboxProps: (record) => ({
        //   props: { disabled: this.arr.some((item) => item.id === record.id) },
        // }),
        getCheckboxProps: this.getCheckboxProps,
      };
    },
  },

  watch: {
    pageVisible(value) {
      console.log(value, "value");
      if (this.pageModelId != "") {
        this.selectedRowKeys = [this.pageModelId];
      } else {
        this.selectedRowKeys = [];
        // this.selectedRowsInfo = {};
      }
      if (value) {
        this.disableId = [];
        this.tableData.forEach((item) => {
          if (item.prizeType == 1 && item.relationId != this.pageModelId) {
            this.disableId.push(item.relationId);
          }
        });
        this.pageList = [];
        this.selectedRowsInfo = this.goodsInfo;
        console.log(this.goodsInfo);
        this.getCouponList();
      } else {
        this.pagination = {
          showQuickJumper: true,
          total: 0,
          current: 1,
          pageSize: 10,
          showTotal: (total) => `共${total}条`,
          showSizeChanger: true,
          pageSizeOptions: ["10", "20", "50", "100", "200"],
        };
      }
    },
  },

  methods: {
    getTimestamp(date) {
      return new Date(date).getTime();
    },
    closeModal() {
      this.searchParams = {
        couponName: "",
      };
      this.$emit("cancel");
    },
    handleSubmit() {
      this.searchParams = {
        couponName: "",
      };
      this.$emit("confirm", this.selectedRowsInfo);
    },
    tableChange(pagination) {
      if (pagination) {
        this.pagination.current = pagination.current;
        this.pagination.pageSize = pagination.pageSize;
        this.getCouponList();
      }
    },
    async getCouponList() {
      this.tableLoading = true;
      let searchParams = {
        current: this.pagination.current,
        size: this.pagination.pageSize,
        couponStatus: 0,
        ...this.searchParams,
      };
      let res = await this.$get("/coupon/page", {
        ...searchParams,
      });
      if (res && res.returnCode == 1000) {
        if (res.dataInfo != null) {
          this.pageList = res.dataInfo.records;
          this.pagination.total = res.dataInfo.total;
        }
      }
      this.tableLoading = false;
    },
    onSelectChange(selectedRowKeys, selectedRows) {
      console.log("selectedRowKeys changed: ", selectedRows);
      console.log("selectedRowKeys changed: ", selectedRowKeys);
      // 修复已选中当时样式未选中的问题。
      this.pageList.forEach((item) => {
        item.active = false;
      });
      this.$set(this.pageList, this.pageList);
      this.selectedRowKeys = selectedRowKeys;
      this.selectedRowsInfo = selectedRows[0];
    },
    getCheckboxProps(record) {
      return {
        props: {
          // disabled: record.id === "450339775862276096",
          disabled:
            this.disableId.some((item) => {
              return record.id === item;
            }) ||
            record.couponIngStatus == "已结束" ||
            record.couponStocks == 0,
        },
      };
    },
    onSearch() {
      this.getCouponList();
    },
    resetSearch() {
      this.searchParams = {
        couponName: "",
      };
      this.getCouponList();
    },
  },
};
</script>

<style lang='less' scoped>
.cardPrice {
  white-space: nowrap;
}
.searchBox {
  margin-bottom: 10px;
  width: 100%;
  display: flex;
  justify-content: flex-end;
}
</style>
